package com.wswy.wzcx.ui.main.mine

import android.arch.lifecycle.Observer
import android.content.Context
import android.os.Bundle
import android.os.SystemClock
import android.support.v4.content.ContextCompat
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.SizeUtils
import com.blankj.utilcode.util.ToastUtils
import com.facebook.common.util.UriUtil
import com.google.android.flexbox.FlexboxLayout
import com.wswy.wzcx.R
import com.wswy.wzcx.aanewApi.baseUtils.Toast
import com.wswy.wzcx.api.ConfigsKt
import com.wswy.wzcx.model.DataCenter
import com.wswy.wzcx.model.UserMode
import com.wswy.wzcx.model.home.ExtModule
import com.wswy.wzcx.model.home.RPaths
import com.wswy.wzcx.model.home.RouterUtils
import com.wswy.wzcx.module.MessageCenter
import com.wswy.wzcx.module.RuntimeContext
import com.wswy.wzcx.module.base.CBaseFragment
import com.wswy.wzcx.module.base.onClick
import com.wswy.wzcx.statistics.StatTools
import com.wswy.wzcx.statistics.StatisticsId
import com.wswy.wzcx.ui.activity.MineActivity
import com.wswy.wzcx.ui.fragment.SettingFragment
import com.wswy.wzcx.ui.fragment.UserInfoFragment
import com.wswy.wzcx.ui.main.ad.AdItemVo
import com.wswy.wzcx.ui.main.ad.HomeAdViewModel
import com.wswy.wzcx.ui.web.WebViewActivity
import com.wswy.wzcx.utils.ShareHelper
import com.wswy.wzcx.utils.Tools
import com.wswy.wzcx.utils.UiUtils
import com.wswy.wzcx.widget.drawable.PolylineDrawable
import com.wswy.wzcx.widget.home.HomeCategoryLayout
import com.wswy.wzcx.widget.home.ModuleItemClickListener
import kotlinx.android.synthetic.main.fragment_nav_mine2.*
import java.util.*
import kotlin.concurrent.schedule

/**
 * 我的
 */
class MainMineFragment : CBaseFragment() {

    private lateinit var mineViewModel: MineViewModel

    private lateinit var homeAdViewModel: HomeAdViewModel

    private lateinit var categoryLayout: HomeCategoryLayout

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val inflate = inflater.inflate(R.layout.fragment_nav_mine2, container, false)
        UiUtils.injectStatusBar(inflate.findViewById(R.id.rl_top))
        return inflate
    }


    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        mineViewModel = provideViewModel(MineViewModel::class.java)
        mineViewModel.onCreate()

        homeAdViewModel = provideViewModelFromActivity(HomeAdViewModel::class.java)

        homeAdViewModel.getMineAdBannerLiveData().observe(this, Observer {
            it?.run {
                if (type == AdItemVo.TTAD) {
                    showBannerAd()
                }
            }

        })
        initViews()
        clickListener()
        regObserves()
    }

    override fun onResume() {
        super.onResume()
        if (RPaths.comment_market) {
            RPaths.comment_market = false
            ShareHelper.gotoMarketResult(context)
        }
    }

    private fun showBannerAd() {
        if (RuntimeContext.isPaidChannel()) {
            homeAdViewModel.loadBannerView(requireActivity()) {

                fl_ad_container.visibility = View.VISIBLE
                fl_ad_container.removeAllViews()
                fl_ad_container.addView(it)
            }
        }
    }


    private fun initViews() {
        view_order_line.background = PolylineDrawable(view_order_line.context)

        //配置
        if (!this::categoryLayout.isInitialized) {
            categoryLayout = HomeCategoryLayout(context).apply {
                setBackgroundResource(R.drawable.shape_while_10dp)
                setLineMaxItem(3)
                setRowHeight(SizeUtils.dp2px(93f))
                setOnItemClickListener(ModuleItemClickListener(StatisticsId.mine_module))
                showHorizontalDivider(ContextCompat.getDrawable(context, R.drawable.list_divider_h))
                showVerticalDivider(ContextCompat.getDrawable(context, R.drawable.list_divider_v))
                showDivider(FlexboxLayout.SHOW_DIVIDER_MIDDLE)
            }

            fl_settings.addView(categoryLayout, ViewGroup.MarginLayoutParams(ViewGroup.MarginLayoutParams.MATCH_PARENT, ViewGroup.MarginLayoutParams.WRAP_CONTENT)
                    .apply {
                        leftMargin = SizeUtils.dp2px(10f)
                        rightMargin = SizeUtils.dp2px(10f)

                    })
        }


//        val models = arrayListOf<MineModel>().apply {
//
//            MineModel("我的爱车","my_cars",R.drawable.mine_mycar,::clickToPage).run { add(this) }
//
//            MineModel("养车账本","yczb",R.drawable.mine_zhangben,::clickToPage).run { add(this) }
//
//            MineModel("附近的车管所","cgs",R.drawable.mine_cheguansuo,::clickToPage).run { add(this) }
//
//            MineModel("违章代办","wzdb",R.drawable.mine_weizhangdaiban,::clickToPage).run { add(this) }
//
//            MineModel("罚款代缴","fkdj",R.drawable.mine_fakuandaijiao,::clickToPage).run { add(this) }
//
//            MineModel("交管12123","web12123_faq",R.drawable.mine_12123,::clickToPage).run { add(this) }
//
//            MineModel("意见反馈","feedback",R.drawable.mine_feedback,::clickToPage).run { add(this) }
//
//            MineModel("介绍给朋友","share_app",R.drawable.mine_sharetofriend,::clickShare).run { add(this) }
//
//            MineModel("联系客服","contact",R.drawable.mine_contectserive,::clickToPage).run { add(this) }
//
//        }

        //showModules(models)

    }


    private fun showModules(list: List<ExtModule>) {
        categoryLayout.showCategory(list)
        val row = categoryLayout.row
        UiUtils.addOnGlobalLayoutListener(categoryLayout) {
            if (it.height > 0) {
                //行高+底部间距
                val h = row * SizeUtils.dp2px(93f) + SizeUtils.dp2px(10f)
                fl_settings.layoutParams?.run {
                    this.height = h
                    fl_settings.layoutParams = this
                }

            }

        }

    }


    private fun clickListener() {

        //设置
        image_btn_setting.onClick {
            startActivity(MineActivity.asIntent(context, SettingFragment.TAG))
        }
        //消息
        image_btn_message.onClick {
            RouterUtils.start(context, RPaths.message)

        }
        //用户信息
        ll_user.onClick {
            if (mineViewModel.hasLogin()) {
                startActivity(MineActivity.asIntent(context, UserInfoFragment.TAG))
            } else {
                mineViewModel.gotoLogin(it.context)
            }
        }

        //订单列表
        ll_order_processing.onClick {
            startOrder(it.context, 1, StatisticsId.mine_order_processing)

        }
        ll_order_completed.onClick {

            startOrder(it.context, 2, StatisticsId.mine_order_done)
        }
        ll_order_refund.onClick {
            startOrder(it.context, 3, StatisticsId.mine_order_failure)
        }

        ll_order_all.onClick {
            startOrder(it.context, 0, StatisticsId.mine_order_all)
        }

        var lastClick: Long = 0
        var clickCount: Long = 0

        img_main_logo.setOnClickListener {

            if (clickCount > 3) {
                RouterUtils.start(it.context, "_test")
                clickCount = 0
                lastClick = 0
            } else {

                val curr = SystemClock.elapsedRealtime()

                if (lastClick == 0L || curr - lastClick < 500) {
                    clickCount++

                } else {
                    clickCount = 0
                }
                lastClick = curr
            }

        }

    }

    private fun startOrder(context: Context, position: Int, sid: String) {
        if (DataCenter.get().hasLogin()) {
            WebViewActivity.startWebview(context, ConfigsKt.H5_ORDER_LIST().format(position, DataCenter.get().userMode?.token))
        } else {
            mineViewModel.gotoLogin(context)
        }
        StatTools.sendClick(context, sid)
    }

    private fun regObserves() {
        mineViewModel.getUserLiveData().observe(this, Observer {
            fillUserInfo(it)
        })
        mineViewModel.getCityLiveData().observe(this, Observer {
            if (mineViewModel.hasLogin() && it != null) {

                tv_local_vip.visibility = View.VISIBLE
                tv_local_vip.text = getString(R.string.mine_car_member, it.replace("市", ""))
            } else {
                tv_local_vip.visibility = View.GONE
            }
        })

        MessageCenter.getMsgUnreadCountLiveData().observeForever {

            if (badgeView != null) {

                it?.run {
                    if (DataCenter.get().hasLogin()) {

                        if (isOk() && data ?: 0 > 0) {
                            badgeView.badgeCount = data
                        } else {
                            badgeView.text = null
                        }
                    } else {
                        badgeView.text = null
                    }

                } ?: kotlin.run {
                    badgeView.text = null
                }
            }
        }

        MessageCenter.getFeedbackCountLiveData().observeForever {


            it?.run {

                if (isOk()) {
                    updateFeedback(data)
                }

            } ?: kotlin.run {
                categoryLayout.updateSignByTag(RPaths.feedback, null)
            }
        }


        mineViewModel.getMineModels().observe(this, Observer {
            it?.run {
                showModules(this)
                updateFeedback(MessageCenter.getFeedbackCountLiveData().value?.data)

            }
        })

    }


    private fun updateFeedback(count: Int?) {
        count?.run {

            if (DataCenter.get().hasLogin()) {

                if (this > 0) {
                    categoryLayout.updateSignByTag(RPaths.feedback, this.toString())
                } else {
                    categoryLayout.updateSignByTag(RPaths.feedback, null)
                }
            } else {
                categoryLayout.updateSignByTag(RPaths.feedback, null)
            }
        } ?: kotlin.run {
            categoryLayout.updateSignByTag(RPaths.feedback, null)
        }
    }


    private fun fillUserInfo(userMode: UserMode?) {
        userMode?.let {
            //已登录
            if (TextUtils.isEmpty(it.headImg)) {
                image_view_header.setImageURI(UriUtil.getUriForResourceId(R.drawable.avatar_highlight), null)
            } else {

                image_view_header.setImageURI(it.headImg)
            }
            tv_user_name.text = userMode.nickName

        } ?: kotlin.run {
            //未登录
            image_view_header.setImageURI(UriUtil.getUriForResourceId(R.drawable.avatar_highlight), null)
            tv_local_vip.visibility = View.GONE
            tv_user_name.text = "还未登录，请登录"

        }
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if (!hidden) {
            mineViewModel.reloadUserInfo()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        MessageCenter.getFeedbackCountLiveData().removeObservers(this)
        MessageCenter.getMsgUnreadCountLiveData().removeObservers(this)
    }
}